using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using backend.Data;
using backend.Models;
using backend.Models.Dtos;
using Microsoft.EntityFrameworkCore;

namespace backend.Repositories
{
    public class ProfessionRepo : BaseRepo<CampusFacilityRepairManagementDbContext, Profession>
    {
        private readonly IMapper _mapper;
        private readonly CampusFacilityRepairManagementDbContext _context;
        public ProfessionRepo(CampusFacilityRepairManagementDbContext context, IMapper mapper) : base(context)
        {
            _mapper = mapper;
            _context = context;
        }

        public async Task<Profession> CreateProfessionAsync(string ID, string professionName)
        {
            var profession = new Profession { PId = ID, PName = professionName };
            await DbSet.AddAsync(profession);
            await SaveChangesAsync();
            return profession;
        }

        /// <summary>
        /// 删除指定ID的工种
        /// </summary>
        /// <param name="pid">要删除的工种ID</param>
        /// <returns>操作是否成功</returns>
        public async Task<bool> DeleteProfessionAsync(string pid)
        {
            var profession = await DbSet.FindAsync(pid);
            if (profession != null)
            {
                if (profession.PId == "DFP")
                {
                    throw new Exception("不能删除待分配工种");
                }
                DbSet.Remove(profession);
                await SaveChangesAsync();
                return true;
            }
            return false;
        }

        public async Task<List<ProfessionDto>> GetProfessionsAsync()
        {
            var professions = await DbSet.ToListAsync();

            var professionDtos = professions.Select(profession => new ProfessionDto
            {
                Value = profession.PId,
                Label = profession.PName
            }).ToList();

            return professionDtos;
        }


        /// <summary>
        /// 保存更改到数据库
        /// </summary>
        public async Task SaveChangesAsync()
        {
            await Context.SaveChangesAsync();
        }
    }
}